package cn.whitecao.contentcenter.controller;

import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
import com.alibaba.csp.sentinel.adapter.servlet.callback.WebCallbackManager;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author ：腼腆的老黄.
 * @date ：Created in 2019-10-09 16:31
 */
@Component
public class MyUrlBolckHandler implements UrlBlockHandler {
    public MyUrlBolckHandler() {
        WebCallbackManager.setUrlBlockHandler(new UrlBlockHandler() {
            @Override
            public void blocked(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws IOException {
                ErrMsg errMsg=new ErrMsg();
                if (e instanceof FlowException){
                    errMsg.setCode(500);
                    errMsg.setMsg("被限流了");
                }else {
                    errMsg.setCode(500);
                    errMsg.setMsg("被降级了");
                }
                httpServletResponse.setStatus(500);
                httpServletResponse.setCharacterEncoding("utf-8");
                httpServletResponse.setHeader("content-type","application/json;charset=UTF-8");
                httpServletResponse.setContentType("application/json;charset=UTF-8");
                new ObjectMapper().writeValue(httpServletResponse.getWriter(),errMsg);
            }
        });
    }

    @Override
    public void blocked(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws IOException {

        ErrMsg errMsg=new ErrMsg();
        if (e instanceof FlowException){
            errMsg.setCode(500);
            errMsg.setMsg("被限流了");
        }else {
            errMsg.setCode(500);
            errMsg.setMsg("被降级了");
        }
        httpServletResponse.setStatus(500);
        httpServletResponse.setCharacterEncoding("utf-8");
        httpServletResponse.setHeader("content-type","application/json;charset=UTF-8");
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        new ObjectMapper().writeValue(httpServletResponse.getWriter(),errMsg);
        //httpServletResponse.
    }

    @Data
    public static class ErrMsg{
        private Integer code;
        private String msg;
    }
}
